package DynamicProgram.zero_onebag;

/**
 * @ClassName BagProblem
 * @Description TODO
 * @Author lenovo
 * @Date 2023-07-12 11:22
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class BagProblem {
    public static void main(String[] args) {
        int[] weight = {1, 3, 4};
        int[] value = {15, 20, 30};
        int bagSize = 4;
        testWeightBagProblem(weight, value, bagSize);
    }

    /**
     * 动态规划获得结果
     *
     * @param weight  物品的重量
     * @param value   物品的价值
     * @param bagSize 背包的容量
     */
    public static void testWeightBagProblem(int[] weight, int[] value, int bagSize) {
        int goodSize = weight.length;
        //i 代指物品的重量 ，j 代指 背包的大小，dp[i][j] 表示从下标为[0-i]的物品里任意取，放进容量为j的背包，价值总和最大是多少。
        int[][] dp = new int[goodSize][bagSize + 1];
        for (int i = weight[0]; i <= bagSize; i++) {
            dp[0][i] = value[0];
        }

        //i 第i个物品的物品重量
        for (int i = 1; i < weight.length; i++) {
            //j 背包的重量
            for (int j = 1; j <= bagSize; j++) {
                //如果背包能承受的重量小于物品的重量,说明背包放不下就取上一个物品在背包承受重量j的重量的最大值
                if (j < weight[i]) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]);
                }
            }
        }
        for (int i = 0; i < goodSize; i++) {
            for (int j = 0; j <= bagSize; j++) {
                System.out.print(dp[i][j] + "\t");
            }
            System.out.println("");
        }
    }
}